const prizeDraw =
    storage.getGroupStorage<{ name: string; userId: string }[]>('prizeDraw')!;

setInterval(async () => {
    const value = await prizeDraw.get('data')!;
    let data = value?.value || [];
    const users = world.querySelectorAll('player').map((e) => {
        return { name: e.player.name, userId: e.player.userId };
    });
    data = data.filter((e) => !users.some((f) => f.userId === e.userId));
    data.push(...users);
    await prizeDraw.set('data', data);
}, 1000 * 10);

world.onChat(async ({ entity, message }) => {
    if (message !== '抽奖') {
        return;
    }
    if (
        entity.player?.userId === '13048627' ||
        entity.player?.userId === '50041641'
    ) {
        const data = (await prizeDraw.get('data'))!.value;
        const winners1: { name: string; userId: string }[] = [];
        const winners2: { name: string; userId: string }[] = [];
        const winners3: { name: string; userId: string }[] = [];
        // 修复：添加保护逻辑防止无限循环
        const maxWinners1 = Math.min(5, data.length);
        const maxWinners2 = Math.min(10, data.length);
        while (winners1.length < maxWinners1) {
            const index = Math.floor(Math.random() * data.length);
            const user = data[index];
            if (!winners1.some((e) => e.userId === user.userId)) {
                winners1.push(user);
            }
        }
        while (winners2.length < maxWinners2) {
            const index = Math.floor(Math.random() * data.length);
            const user = data[index];
            if (!winners2.some((e) => e.userId === user.userId)) {
                winners2.push(user);
            }
        }
        while (winners3.length < maxWinners1) {
            const index = Math.floor(Math.random() * data.length);
            const user = data[index];
            if (!winners3.some((e) => e.userId === user.userId)) {
                winners3.push(user);
            }
        }
        world.querySelectorAll('player').forEach((e) => {
            e.player.dialog<GameTextDialogParams>({
                type: GameDialogType.TEXT,
                content: `恭喜\n${winners1.map((e) => e.name + '(' + e.userId + ')').join('、\n')}\n抽中香肠头像框\n\n` +
                         `恭喜\n${winners2.map((e) => e.name + '(' + e.userId + ')').join('、\n')}\n抽中勇士皮肤\n\n` +
                         `恭喜\n${winners3.map((e) => e.name + '(' + e.userId + ')').join('、\n')}\n抽中云岫头像框\n`,
            });
        });
    }
});